package me.jastz.oauth2.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;

/**
 * Created by zhiwen on 2017/8/11.
 */
@EnableWebSecurity
public class WebSecurityConfig {

    /*@Configuration
    @Order(10000)
    public static class ApiWebSecurityAdapter extends WebSecurityConfigurerAdapter {
        private Logger logger = LoggerFactory.getLogger(getClass());

        @Override
        public void configure(HttpSecurity http) throws Exception {
            logger.info("config /api/** order 10000");
            http.antMatcher("/api/**")
                    .authorizeRequests()
                    .anyRequest().hasRole("ADMIN");
        }


    }*/

    @Configuration
//    @Order
    public static class FormLoginWebSecurityAdapter extends WebSecurityConfigurerAdapter {
        private Logger logger = LoggerFactory.getLogger(getClass());

        @Override
        public void configure(HttpSecurity http) throws Exception {
            logger.info("init WebSecurityConfigurerAdapter");
            http.authorizeRequests()
                    .antMatchers("/webjars/**", "/resources/**", "/swagger-ui.html"
                            , "/swagger-resources/**", "/v2/api-docs", "index.html", "/oauth/token"
                            , "/oauth/authorize", "/swagger").permitAll()
                    .anyRequest().authenticated()
                    .and().formLogin()
                    .loginPage("/login").permitAll().successHandler(successHandler()).and().logout()
                    .permitAll();
        }


        /**
         * Spring security 登入成功后跳转到之前的页面
         *
         * @return
         */
        public AuthenticationSuccessHandler successHandler() {
            SimpleUrlAuthenticationSuccessHandler successHandler = new SimpleUrlAuthenticationSuccessHandler();
            successHandler.setUseReferer(true);//设为true就会自动跳转到登入页面
            return successHandler;
        }

    }
}
